package com.huse.usermanager.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huse.commonutls.ApiResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 当用户没有访问资源时候的配置
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private  static ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void commence(HttpServletRequest httpServletRequest,
                         HttpServletResponse response,
                         AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(
                objectMapper.writeValueAsString(
                        ApiResult.error().message("请先登陆！！")
                ));
    }
}